package com.abe.libfitness.main.program;

import android.widget.TextView;

import com.abe.libfitness.R;
import com.abe.libfitness.R2;
import com.abe.libfitness.base.BaseComTempActivity;
import com.abe.libfitness.entity.ComReceiveDataBean;
import com.abe.libfitness.entity.FitnessCustomEntity;
import com.abe.libfitness.utils.CMDConts;
import com.abe.libfitness.utils.ConstantFitness;
import com.abe.libfitness.utils.DataCovertUtil;
import com.abe.libfitness.widget.CircleChartView;
import com.abe.libquick.utils.quick.EmptyUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class FitnessCustomActivity extends BaseComTempActivity {
    @BindView(R2.id.item_title)
    public TextView itemTitle;

    @BindView(R2.id.report_number)
    public TextView showTargetNumber;
    @BindView(R2.id.report_number2)
    public TextView mTimeTv;
    @BindView(R2.id.report_number3)
    public TextView mCalorieTv;
    @BindView(R2.id.report_number4)
    public TextView mShowWeight;
    @BindView(R2.id.myview_circle_chart)
    public CircleChartView mDialChartView;

    private int mWeight1;
    private int mWeight2;
    private int mWeight3;
    private boolean firstTime = true;
    /**
     * 计算器
     */
    private Calendar mCalendar = Calendar.getInstance();
    private Timer timer;
    private Timer mTimer4LogOut = null;
    private int distance = 0;
    private int weight = 0;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_fitness_custom;
    }

    @Override
    protected void initContent() {
        if (EmptyUtils.isEmpty(bundle()) || !bundle().containsKey(ConstantFitness.TARGET)) {
            finish();
            return;
        }
        FitnessCustomEntity entity = bundle().getParcelable(ConstantFitness.TARGET);
        if (EmptyUtils.isEmpty(entity)) {
            finish();
            return;
        }
        mWeight1 = entity.getWeight01();
        mWeight2 = entity.getWeight02();
        mWeight3 = entity.getWeight03();
        if (mWeight1 < 10) {
            mWeight1 = 10;
        }
        if (mWeight2 < 10) {
            mWeight2 = 10;
        }
        if (mWeight3 < 10) {
            mWeight3 = 10;
        }
        mSendThread = new SendThread(getForceCMD(), false);
        mSendThread.start();
    }

    @OnClick(R2.id.iv_back)
    public void back() {
        finish();
    }

    protected List<byte[]> getForceCMD() {
        List<String> forceList;
        StringBuilder sDistance_D2 = new StringBuilder(); // 存放写入力量寄存器2命令
        StringBuilder sDistance_D3 = new StringBuilder(); // 存放写入力量寄存器2命令
        StringBuilder sDistance_D4 = new StringBuilder(); // 存放写入力量寄存器2命令
        StringBuilder sDistance_D5 = new StringBuilder(); // 存放写入力量寄存器2命令
//        int distance_3 = 0; // 存放距离寄存器3的值
        List<byte[]> cmdList = new ArrayList<>(); // 命令列表
        List<String> forceHeadList = new ArrayList<>(); // 写入力量命令列表
        forceHeadList.add(CMDConts.CMD_WRITE_REIGSTER_F1); // 添加命令头部
        forceHeadList.add(CMDConts.CMD_WRITE_REIGSTER_F2);
        forceHeadList.add(CMDConts.CMD_WRITE_REIGSTER_F3);
        forceHeadList.add(CMDConts.CMD_WRITE_REIGSTER_F4);
        forceHeadList.add(CMDConts.CMD_WRITE_REIGSTER_F5);
        cmdList.add(CMDConts.CMD_WRITE_REIGSTER_F0);
        forceList = getProtForce();
        if (forceList != null) {
            for (int i = 0; i < forceHeadList.size(); i++) {
                StringBuilder sBuilder = new StringBuilder();
                sBuilder.append(forceHeadList.get(i)); // 添加头部
                sBuilder.append(forceList.get(i)); // 添加力量值
                // 获得并添加CRC校验码
                cmdList.add(DataCovertUtil.getCRC(DataCovertUtil.HexToByteArr(sBuilder.toString())));
            }
        }
//        distance_3 = (80 + 3500) / 2; // 计算距离寄存器D3的值
        sDistance_D2.append(CMDConts.CMD_WRITE_REIGSTER_D2); // 添加头部
        sDistance_D2.append(DataCovertUtil.get4LenString(Integer.toHexString(700))); // 计算并添加距离值
        sDistance_D3.append(CMDConts.CMD_WRITE_REIGSTER_D3); // 添加头部
        sDistance_D3.append(DataCovertUtil.get4LenString(Integer.toHexString(1400))); // 添加距离值
        sDistance_D4.append(CMDConts.CMD_WRITE_REIGSTER_D4); // 添加头部
        sDistance_D4.append(DataCovertUtil.get4LenString(Integer.toHexString(2100)));// 添加距离值
        sDistance_D5.append(CMDConts.CMD_WRITE_REIGSTER_D5); // 添加头部
        sDistance_D5.append(DataCovertUtil.get4LenString(Integer.toHexString(3500))); // 添加距离值
        cmdList.add(CMDConts.CMD_WRITE_REIGSTER_D0); // 添加距离寄存器D0的命令
        cmdList.add(CMDConts.CMD_WRITE_REIGSTER_D1); // 添加距离寄存器D1的命令
        cmdList.add(DataCovertUtil.getCRC(DataCovertUtil.HexToByteArr(sDistance_D2.toString()))); // 计算并添加距离寄存器D2命令的CRC校验码
        cmdList.add(DataCovertUtil.getCRC(DataCovertUtil.HexToByteArr(sDistance_D3.toString()))); // 计算并添加距离寄存器D3命令的CRC校验码
        cmdList.add(DataCovertUtil.getCRC(DataCovertUtil.HexToByteArr(sDistance_D4.toString()))); // 计算并添加距离寄存器D4命令的CRC校验码
        cmdList.add(DataCovertUtil.getCRC(DataCovertUtil.HexToByteArr(sDistance_D5.toString()))); // 计算并添加距离寄存器D5命令的CRC校验码
        cmdList.add(CMDConts.CMD_READ_REGISTER_3_4); // 添加读取寄存器3、4命令
        return cmdList;
    }

    /**
     * 获得变力力量
     */
    private List<String> getProtForce() {
        int force1 = mWeight1 * 333 / 10;
        int force3 = mWeight2 * 333 / 10;
        int force5 = mWeight3 * 333 / 10;
        int force2 = (force1 + force3) / 2;
        int force4 = (force3 + force5) / 2;
        List<String> list = new ArrayList<>();
        list.add(DataCovertUtil.get4LenString(Integer.toHexString(force1))); // 获得四位字符串型力量的值
        list.add(DataCovertUtil.get4LenString(Integer.toHexString(force2))); // 获得四位字符串型力量的值
        list.add(DataCovertUtil.get4LenString(Integer.toHexString(force3))); // 获得四位字符串型力量的值
        list.add(DataCovertUtil.get4LenString(Integer.toHexString(force4))); // 获得四位字符串型力量的值
        list.add(DataCovertUtil.get4LenString(Integer.toHexString(force5))); // 获得四位字符串型力量的值
        return list;
    }

    private void resetCalendar() {
        mCalendar.set(Calendar.HOUR_OF_DAY, 0);
        mCalendar.set(Calendar.MINUTE, 0);
        mCalendar.set(Calendar.SECOND, 0);
    }

    private void showClock(TextView tv) {
        timer = new Timer();
        timer.schedule(new TrainTask(tv), 1000, 1000);
    }

    private void resetTimer4LogOut() {
        if (mTimer4LogOut != null) {
            mTimer4LogOut.cancel();
            mTimer4LogOut.purge();
            mTimer4LogOut = null;
        }
        mTimer4LogOut = new Timer();
        // 1分钟不操作自动上传数据
        mTimer4LogOut.schedule(new Task4Logout(), 60 * 1000);
    }

    @Override
    protected void onDataReceived(ComReceiveDataBean ComRecData) {
        if (ComRecData.verification()) {
            String res = DataCovertUtil.ByteArrToHex(ComRecData.bRec);
            final int control = DataCovertUtil.HexToInt(DataCovertUtil
                    .ByteArrToHex(ComRecData.bRec).substring(2, 4));
            if (control == 3) { // control指的返回的命令区分码
                // 实时值
                weight = DataCovertUtil.HexToInt(res.substring(6, 10));
                runOnUiThread(() -> mShowWeight.setText(String.valueOf((int) (weight / 33.33))));

                distance = DataCovertUtil.HexToInt(res.substring(10, 14));
                if (distance > 150) {
                    if (firstTime) {
                        resetCalendar();
                        showClock(mTimeTv);
                        firstTime = false;
                    }
                    resetTimer4LogOut();
                }

                if (distance >= 1500) { // 检测到距离大于60%最大距离时
                    mStatus = 1; // 拉伸状态变为1
                    if (distance4Calorie < distance) {
                        distance4Calorie = distance;
                    }
                }

                // 拉伸状为1并且 检测到距离小于30%最大距离时拉伸状态变为
                if (mStatus == 1 && distance < 1500) {
                    mRealCounts++; // 次数 + 1
                    mStatus = 0; // 拉伸状态清除

                    if (distance4Calorie >= 1500 && distance4Calorie < 2000) {
                        calorie = calorie + (weight / (180 + (Math.random() * 40)));
                    } else if (distance4Calorie >= 2000 && distance4Calorie < 3000) {
                        calorie = calorie + (weight / (130 + (Math.random() * 40)));
                    } else {
                        calorie = calorie + (weight / (80 + (Math.random() * 40)));
                    }
                }

                runOnUiThread(() -> {
                    showTargetNumber.setText(String.valueOf(mRealCounts));
                    mCalorieTv.setText(String.format(Locale.CHINA, "%.1f", calorie));
                    mDialChartView.setPercent(distance * 100 / 3500, 3500 * 100 / 3500);
                });
            }
        }
    }

    class TrainTask extends TimerTask {
        TrainTask(TextView tv) {
            mTimeTv = tv;
        }

        @Override
        public void run() {
            runOnUiThread(() -> {
                // 每次秒数+1
                mCalendar.add(Calendar.SECOND, 1);
                mTimeTv.setText(String.format("%s:%s", DataCovertUtil.get2LenString(mCalendar.get(Calendar.MINUTE)), DataCovertUtil.get2LenString(mCalendar.get(Calendar.SECOND))));
            });
        }
    }

    class Task4Logout extends TimerTask {
        @Override
        public void run() {
            runOnUiThread(FitnessCustomActivity.this::finish);
        }
    }
}